package com.study.demo;

import java.util.List;

import org.flowable.bpmn.model.Activity;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.InclusiveGateway;
import org.flowable.bpmn.model.ParallelGateway;
import org.flowable.bpmn.model.SequenceFlow;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.TaskService;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class DealMultiInstanceTurnDown {

	@Autowired 
	private TaskService taskService;
	@Autowired 
	private ProcessDefinitionUtils processDefinitionUtils;
	@Autowired 
	private ManagementService managementService;
	
	@Autowired 
	private HistoryService historyService;
	
	public void backToStep(FlowElement currentflowElement,String currentProcessInstanceId) {
		TaskEntity taskEntity = (TaskEntity) taskService.createTaskQuery().processInstanceId(currentProcessInstanceId).singleResult();
		
		if(taskEntity != null) {
			//1.获取活动
			Activity activity = processDefinitionUtils.findFlowElementById(taskEntity.getProcessDefinitionId(), currentflowElement.getId());
			
			//2.判断上个节点是不是并行网关
			if(activity != null) {
				//获取入线
				List<SequenceFlow>  sequenceFlows = activity.getIncomingFlows();
				
				if(!CollectionUtils.isEmpty(sequenceFlows)) {
					
					for (SequenceFlow sequenceFlow : sequenceFlows) {
						FlowElement upNode = sequenceFlow.getSourceFlowElement();
						if(upNode != null && (upNode instanceof ParallelGateway || upNode instanceof InclusiveGateway)) {
							System.out.println("并行网关，不能驳回");
							return ;
						}
					}
				}
				
				//3.删除当前执行实例
				managementService.executeCommand(new DeleteTaskCmd(currentProcessInstanceId));
				
				//4.删除历史活动
				managementService.executeCommand(new DeleteHisActivitiesCmd(currentProcessInstanceId));
				
				//5. 驳回到disk节点
                Activity currActivity = processDefinitionUtils.findFlowElementById(taskEntity.getProcessDefinitionId(), taskEntity.getTaskDefinitionKey());
                
//                if(currActivity) {
//                	参考：https://blog.csdn.net/liuwenjun05101/article/details/82534102
//                }
			}
		}
		
	}
}
